import re
import requests
import ssl
import urllib2
import urllib
import time
from PIL import Image
import json
import os
import cookielib



class zhihu_login(object):
    def __init__(self):
        self.login_url="https://www.zhihu.com/"
        self.captcha_url="https://www.zhihu.com/captcha.gif"
        self.session=requests.session()

    def getContent(self,url):
        r=self.session.get(url,headers=header,verify=False)
        #print(r.content)
        return r.content

    def getXSRF(self):
        content=self.getContent(self.login_url)
        pattern=re.compile('.*?<input type="hidden" name="_xsrf" value="(.*?)"/>.*?')
        match=re.findall(pattern,content)
        xsrf=match[0]
        return xsrf
    def get_captcha(self):
        t = str(int(time.time() * 1000))
        captcha_url =self.captcha_url+ '?r=' + t + "&type=login"

        s=session.get(captcha_url,headers=header,verify=False)
    
        f=open('cptcha.gif','wb')

        f.write(s.content)
        f.close()


        # urllib.urlretrieve(captcha_url, 'cptcha.gif')
        # image_data = request.urlopen(captcha_url).read()
        # with open('cptcha.gif', 'wb') as f:
        #     f.write(image_data)
        im = Image.open('cptcha.gif')
        im.show()
        captcha = raw_input('input captcha:')
        return captcha
    def login(self):
        
        login_data = {
            "_xsrf":self.getXSRF(),
            "remenberme":"true",
            "password":"9459wtang",
            "phone_num":"15682051720",
            "captcha":self.get_captcha()     
        }

        header['Referer']=self.login_url
        base_url=self.login_url+"login/phone_num"
        response=session.post(base_url,headers=header,data=login_data,verify=False)

        print(response.content)

if __name__=="__main__":
    zhihu_login().login()    